package com.sanjishu.enterlab.electricity.sale.shiro;

import com.sanjishu.enterlab.electricity.sale.domain.Admin;
import com.sanjishu.enterlab.electricity.sale.domain.User;
import com.sanjishu.enterlab.electricity.sale.service.AdminService;
import com.sanjishu.enterlab.electricity.sale.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

public class AuthRealm extends AuthorizingRealm {

	private static final Logger log = LoggerFactory.getLogger(AuthRealm.class);

	@Autowired
	private UserService userService;
	@Autowired
	private AdminService adminService;

	//@Autowired
	//private PrivilegeService privilegeService;

	public AuthRealm() {
		super();
	}

	 /**
     * 授权
     */
	@Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		if (!SecurityUtils.getSubject().isAuthenticated()) {
			doClearCache(principalCollection);
			SecurityUtils.getSubject().logout();
			return null;
		}

		ShiroAdmin user = (ShiroAdmin) principalCollection.getPrimaryPrincipal();
		if (user == null) {
			return null;
		}
		log.info("获取用户权限:{}", user.getId());

		// 权限信息
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		try {
//			List<String> permissions = privilegeService.findAdminPrivileges(user.getId());
			List<String> permissions = new ArrayList<>();
			info.addStringPermissions(permissions);
		} catch (Exception e) {
			log.error(e.getMessage());
		}

		return info;
    }

	/**
	 *  认证信息
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {

		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		String username = token.getUsername();

		User user = userService.findByPhone(username);
		//Admin admin = adminService.findByPassport(username);

		if(user != null) {
			log.info("认证用户:{}", user.getId());
			ShiroAdmin shiroAdmin = new ShiroAdmin(user.getId(), user.getPhone(), user.getPhone(), user.getTypes());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(shiroAdmin, user.getPassword(), getName());
			return info;
		}
//		else if (admin != null) {
//			log.info("认证用户:{}", admin.getId());
//			ShiroAdmin shiroAdmin = new ShiroAdmin(admin.getId(), admin.getCellphone(), admin.getName());
//			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(shiroAdmin, admin.getPassword(), getName());
//			return info;
//		}
		return null;

	}

	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(
				principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 设定Password校验.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		SimpleCredentialsMatcher matcher = new SimpleCredentialsMatcher();
		setCredentialsMatcher(matcher);
	}
}
